package com.uyayo.oms.system.controller;

import com.uyayo.core.util.PasswordHelper;
import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.message.model.Tree;
import com.uyayo.framework.common.util.CodeUtil;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.oms.system.constants.FileDirConstants;
import com.uyayo.oms.system.util.PathUtil;
import com.uyayo.oms.system.vo.SysUserVO;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageOrderCondition;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.system.authority.model.SysUserCondition;
import com.uyayo.system.authority.service.SysUserService;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 
 * <p>
 * Title: SysUserController
 * </p>
 * <p>
 * Description:用户的controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller("sysUserController")
@RequestMapping("/system/authority/user")
public class SysUserController {

	@Autowired 
	private SysUserService userService;
	
	@Autowired
	private ParamBiz paramBiz;
	
	@RequestMapping(value="index",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:user:index")
	@MethodName(value="系统管理->权限管理->用户管理")
	public String user_main() {
		return paramBiz.getManagerTemplatesPrefix()+"system/authority/user/index";
	}
	
	@ResponseBody
	@RequestMapping(value="grid",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:user:grid")
	@MethodName(value="系统管理->权限管理->用户管理->查询列表",type=2)
	public PageResult<SysUser> selectUserByPaging(PageOrderCondition pageOrderCondition, SysUserCondition sysUserCondition) throws Exception {
		PageBean<SysUser> pageBean=new PageBean<>(pageOrderCondition.getPageNum(),pageOrderCondition.getPageSize(),pageOrderCondition.getSort(),pageOrderCondition.getOrder());
		try {
			pageBean = userService.selectUserByPaging(pageBean,sysUserCondition);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PageResult<SysUser> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
	}
	
	@ResponseBody
	@RequestMapping("getUserTree")
	public List<Tree> doNotNeedSecurity_getUserTree(SysUserCondition sysUserQUERY) {
		List<SysUser> users= new ArrayList<>();
		try {
			users = userService.selectUser(sysUserQUERY);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		List<Tree> tree = new ArrayList<>();
		for (SysUser user_ : users) {
			Tree node = new Tree();
			node.setId(user_.getId());
			node.setIconCls(user_.getHeadPhoto());
			node.setName(user_.getLoginname());
			tree.add(node);
		}
		return tree;
	}
	
	/*
	 * 进入添加用户页面
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView modelAndView) {
		modelAndView.addObject("fileDir_userInfo",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_INFO));
		modelAndView.addObject("fileDir_userHeadPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_HEADPHOTO));
		modelAndView.addObject("fileDir_userPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_PHOTO));
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/add");
		return modelAndView;
	}
	
	
	/**
	 * 新建一个用户
	 */
	@ResponseBody
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@RequiresPermissions("system:authority:user:save")
	@MethodName(value="系统管理->权限管理->用户管理->新增用户",type=2)
	synchronized public Result saveRole(@Validated SysUserVO sysUserVO ,Errors errors) {
		try {
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUserSession = (SysUser) subject.getPrincipal();
			
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			//执行查询-验证登录账户名唯一
			SysUser sysUserTest = userService.getUserByLoginname(sysUserVO.getLoginname());
			if (sysUserTest != null) {
				return Result.errorAndMsg("账户名已被注册，请更换其它账户名！");
			}
			
			SysUser sysUser = new SysUser();
			sysUser.setId(CodeUtil.getTimeSequenceAsRandomCode());
			sysUser.setNickname(sysUserVO.getNickname());
			sysUser.setLoginname(sysUserVO.getLoginname());
			sysUser.setPassword(sysUserVO.getPassword());
			sysUser.setSignature(sysUserVO.getSignature());
			sysUser.setRemark(sysUserVO.getRemark());
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(sysUser);
			sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserVO.getPassword().getBytes()));
			sysUser.setCreatedBy(sysUserSession.getLoginname());
			sysUser.setCreatedTime(new Date());
			userService.saveUser(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("创建用户成功,初始化密码为: "+sysUserVO.getPassword());
	}
	

	/**
	 * 进入角色查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="系统管理->权限管理->用户管理->查看用户",type=2)
	@RequiresPermissions("system:authority:user:view")
	public ModelAndView show(ModelAndView modelAndView,String id) {
		SysUser sysUser = new SysUser();
		try {
			sysUser = userService.getUserById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("sysUser",sysUser);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/view");
		return modelAndView;
	}
	
	
	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:user:update")
	public ModelAndView update(ModelAndView modelAndView,String id) {
		SysUser sysUser = new SysUser();
		try {
			sysUser = userService.getUserById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelAndView.addObject("fileDir_userInfo",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_INFO));
		modelAndView.addObject("fileDir_userHeadPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_HEADPHOTO));
		modelAndView.addObject("fileDir_userPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_PHOTO));
		modelAndView.addObject("sysUser",sysUser);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/edit");
		return modelAndView;
	}
	
	
	/**
	 * 修改用户
	 */
	@ResponseBody
	@RequestMapping(value="update",method = RequestMethod.POST)
	@RequiresPermissions("system:authority:user:update")
	@MethodName(value="系统管理->权限管理->用户管理->修改用户",type=2)
	synchronized public Result update(@Validated SysUserVO sysUserVO ,Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			
			SysUserCondition sysUserCondition = new SysUserCondition();
			sysUserCondition.setLoginname(sysUserVO.getLoginname());
			
			SysUser sysUser = new SysUser();
			sysUser.setId(sysUserVO.getId());
			sysUser.setLoginname(sysUserVO.getLoginname());
			sysUser.setNickname(sysUserVO.getNickname());
			sysUser.setSignature(sysUserVO.getSignature());
			sysUser.setModifiedTime(new Date());
			sysUser.setRemark(sysUserVO.getRemark());
			userService.updateUser(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}


	/**
	 * 进入重置密码页面
	 */
	@RequestMapping(value = "reset-password", method = RequestMethod.GET)
	@RequiresPermissions("system:authority:user:reset-password")
	public ModelAndView resetPassword(ModelAndView modelAndView,String id) throws Exception {
		SysUser sysUser =userService.getUserById(id);
		modelAndView.addObject("fileDir_userInfo",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_INFO));
		modelAndView.addObject("fileDir_userHeadPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_HEADPHOTO));
		modelAndView.addObject("fileDir_userPhoto",FileDirConstants.splitFileDir(FileDirConstants.SYSTEM_USER_PHOTO));
		modelAndView.addObject("sysUser",sysUser);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/reset-password");
		return modelAndView;
	}


	/**
	 * 重置密码
	 */
	@ResponseBody
	@RequestMapping(value="reset-password",method = RequestMethod.POST)
	@RequiresPermissions("system:authority:user:reset-password")
	@MethodName(value="系统管理->权限管理->用户管理->重置密码",type=2)
	synchronized public Result resetPassword(@Validated SysUserVO sysUserVO ,Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}

			SysUser sysUser = userService.getUserById(sysUserVO.getId());
			sysUser.setId(sysUserVO.getId());
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(sysUser);
			sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserVO.getPassword().getBytes()));
			sysUser.setModifiedTime(new Date());
			sysUser.setRemark(sysUserVO.getRemark());
			userService.updateUser(sysUser);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorAndMsg("保存失败！");
		}
		return Result.successAndMsg("保存成功！");
	}

	/**
	 * 删除记录
	 */
	@ResponseBody
	@RequiresPermissions("system:authority:user:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="系统管理->权限管理->用户管理->删除用户",type=2)
	public Result deleteRole(String id) {
		if (id!=null) {
			try {
				int deleteCount = userService.deleteUser(id);
				if(deleteCount<=0){
					return Result.errorAndMsg("删除失败！");
				}
			} catch (Exception e) {
				e.printStackTrace();
				return Result.errorAndMsg(e.getMessage());
			}
		}else{
			return Result.errorAndMsg("请选择需删除的记录！");
		}
		return Result.successAndMsg("删除成功！");

	}

	
	/**
	 * 进入分配角色表单
	 */
	@RequestMapping(value="assign/role",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:user:assign:role")
	public ModelAndView roleGrantForm(ModelAndView modelAndView,String id) {
		modelAndView.addObject("id",id);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/assign_role");
		return modelAndView;
	}
	
	
	
	/**
	 * 分配角色
	 */
	@ResponseBody
	@RequestMapping(value="assign/role",method=RequestMethod.POST)
	@MethodName(value="系统管理->权限管理->用户管理->分配角色",type=2)
	public Result assignRole(String ids, String userId) {
		try {
			userService.assignUserRoles(ids,userId);
		} catch (Exception e) {
			return Result.errorAndMsg("保存失败");
		}
		return Result.successAndMsg("保存成功");	
	}
	
	/**
	 * 进入分配机构表单
	 */
	@RequestMapping(value="assign/organization",method=RequestMethod.GET)
	@RequiresPermissions("system:authority:user:assign:organization")
	public ModelAndView assignOrganization(ModelAndView modelAndView,String id) {
		modelAndView.addObject("id",id);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"system/authority/user/assign_organization");
		return modelAndView;
	}
	
	/**
	 * 分配机构
	 */
	@ResponseBody
	@RequestMapping(value="assign/organization",method=RequestMethod.POST)
	@MethodName(value="系统管理->权限管理->用户管理->分配机构",type=2)
	public Result assignOrganization(HttpServletResponse response,HttpServletRequest request,String ids,String userId) {
		try {
			userService.grantUserOrganizations(ids,userId);
		} catch (Exception e) {
			return Result.errorAndMsg("保存失败");
		}
		return Result.successAndMsg("保存成功");	
	}
	
	/*@RequestMapping(value = "/exportExcel")
	@MethodName(value="系统管理->权限管理->用户管理->导出Excel",type=2)
	public ModelAndView exportExcel(HSSFWorkbook workbook,HttpServletRequest request,HttpServletResponse response,User user) throws Exception {
		ModelAndView mv = new ModelAndView();
		response.setContentType("text/html;charset=UTF-8");
		ExtMap extMap = this.getParamsToExtMap(request);
		List<User> userList=null;
		try {
			if(user.getLoginname() ==null || "".equals(user.getLoginname())){
				user.setLoginname(null);
			}
			if(user.getNickname() ==null || "".equals(user.getNickname())){
				user.setNickname(null);
			}
			if(user.getSex() ==null || "".equals(user.getSex())){
				user.setSex(null);
			}
			 userList = userService.selectUser(user);
		} catch (Exception e) {
			e.printStackTrace();		
		}
		List<String> headers = new ArrayList<String>();
		List<ExtMap> varList = new ArrayList<ExtMap>();
		headers.add("姓名");  		//1
		headers.add("性别");  		//2
		headers.add("年龄");  		//3
		headers.add("登陆账号");  	//4
		extMap.put("headers", headers);
		try {
			for (int i = 0; i < userList.size(); i++) {
				ExtMap userMap = this.getParamsToExtMap(request);
				userMap.put("var1", userList.get(i).getNickname());		//1
				if(userList.get(i).getSex()!=null && userList.get(i).getSex().equals("1")){
					userMap.put("var2", "男");		//2
				}else if(userList.get(i).getSex()!=null && userList.get(i).getSex().equals("0")){
					userMap.put("var2", "女");		//2
				}else{
					userMap.put("var2", "未知");		//2
				}
				userMap.put("var3", userList.get(i).getAge());		//3
				userMap.put("var4", userList.get(i).getLoginname());//4
				varList.add(userMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		extMap.put("fileName", "用户表");
		extMap.put("varList", varList);
		try {
			ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
			mv = new ModelAndView(erv,extMap);
		} catch (Exception e) {
			e.printStackTrace();	
		}
		return mv;
	}*/
	
	
	/**
	 * 下载模版
	 */
	/*public void downExcel(HttpServletResponse response){

			
		try {
			FileDownload.fileDownload(response, "/upload/file/Users.xls", "Users.xls");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
	
	
	
	/**
	 * 
	 *  @Description 下载文件 
	 *  @author zhangyd 
	 *  @date 2015年12月11日 下午6:11:33 
	 *  @param fileName
	 *  @return
	 *  @throws IOException 
	 **/ 
	@RequestMapping(value="/doNotNeedSecurity_downExcel")
	public ResponseEntity<byte[]> download(String fileName) throws IOException { 
		//将文件转换为二进制文件
		File file = new File(PathUtil.getClasspath()+"upload/file/Users.xls");
		fileName = new String("Users.xls".getBytes("gb2312"), "iso8859-1"); 
		HttpHeaders headers = new HttpHeaders(); 
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
		headers.setContentDispositionFormData("attachment", fileName); 
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); 
	}

	
	/**
	 * 从EXCEL导入到数据库
	 */
	/*@RequestMapping(value="/importExcel")
	@MethodName(value="系统管理->权限管理->用户管理->导入Excel",type=2)
	public ModelAndView importExcel(HttpServletRequest request,@RequestParam(value="excel",required=false) MultipartFile file ) throws Exception{
		ModelAndView mv = new ModelAndView();
		ExtMap pd = this.getParamsToExtMap(request);
		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getClasspath() + "uploadFiles/file/";	//文件上传路径
			String fileName =  FileUpload.fileUp(file, filePath, "userexcel");	//执行上传
			
			List<ExtMap> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);	//执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
			
			存入数据库操作======================================
						
			*//**
			 * var0 :编号
			 * var1 :姓名
			 * var2 :手机
			 * var3 :邮箱
			 * var4 :备注
			 *//*
			for(int i=0;i<listPd.size();i++){
				User user = new User();
				user.setPassword(MD5Util.md5("123456"));  //密码
				user.setId(CodeUtil.getTimeSequenceAsRandomCode());	//ID
				user.setNickname(listPd.get(i).getAsString("var0"));	  	//姓名
				
				String sex = listPd.get(i).getAsString("var1");
				if("男".equals(sex)){
					sex = "1"; 
				}else if("女".equals(sex)){
					sex = "0"; 
				}else{
					sex = ""; 
				}
				user.setSex(sex);//性别
				user.setAge(listPd.get(i).getAsInteger("var2"));//年龄
				user.setLoginname(listPd.get(i).getAsString("var3"));//登陆名
				User userTest = new User();
				userTest = userService.getUserByLoginname(listPd.get(i).getAsString("var3"));
				if(userTest != null){										//判断用户名是否重复
					user.setLoginname(listPd.get(i).getAsString("var3")+CodeUtil.getRandom(4));	//ID
				}				
				user.setTheme("3");
				int countSave = userService.saveUser(user);
			}
			存入数据库操作======================================
			
			mv.addObject("msg","success");
		}
		
		mv.setViewName("save_result");
		return mv;
	}*/
}
